import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/platform_config.dart';
import '../models/show.dart';
import '../providers/show_provider.dart';
import '../utils/theme.dart';

/// 演出搜索界面
class ShowSearchScreen extends StatefulWidget {
  const ShowSearchScreen({super.key});

  @override
  State<ShowSearchScreen> createState() => _ShowSearchScreenState();
}

class _ShowSearchScreenState extends State<ShowSearchScreen>
    with SingleTickerProviderStateMixin {
  final TextEditingController _searchController = TextEditingController();
  late TabController _tabController;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: TicketPlatform.values.length,
      vsync: this,
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('搜索演出'),
        elevation: 0,
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(100),
          child: Column(
            children: [
              // 搜索框
              Padding(
                padding: const EdgeInsets.all(16),
                child: TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    hintText: '搜索演出、电影、艺人...',
                    prefixIcon: const Icon(Icons.search),
                    suffixIcon: IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        _searchController.clear();
                        setState(() {});
                      },
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide.none,
                    ),
                    filled: true,
                    fillColor: Colors.grey[100],
                  ),
                  onSubmitted: _performSearch,
                ),
              ),
              // 平台选择标签
              TabBar(
                controller: _tabController,
                tabs: TicketPlatform.values.map((platform) {
                  final config = PlatformConfig.getConfig(platform);
                  return Tab(
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(config.platformIcon),
                        const SizedBox(width: 4),
                        Text(config.platformName),
                      ],
                    ),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
      body: Consumer<ShowProvider>(
        builder: (context, showProvider, child) {
          return TabBarView(
            controller: _tabController,
            children: TicketPlatform.values.map((platform) {
              return _buildSearchResults(platform, showProvider);
            }).toList(),
          );
        },
      ),
    );
  }

  Widget _buildSearchResults(TicketPlatform platform, ShowProvider showProvider) {
    if (showProvider.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    final results = showProvider.searchResults[platform] ?? [];
    
    if (_searchController.text.isEmpty) {
      return _buildEmptyState('输入关键词开始搜索');
    }

    if (results.isEmpty) {
      return _buildEmptyState('未找到相关演出');
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: results.length,
      itemBuilder: (context, index) {
        final result = results[index];
        return _buildSearchResultCard(platform, result, showProvider);
      },
    );
  }

  Widget _buildEmptyState(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search_off,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            message,
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchResultCard(
    TicketPlatform platform,
    Map<String, dynamic> result,
    ShowProvider showProvider,
  ) {
    final config = PlatformConfig.getConfig(platform);
    
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 2,
      child: InkWell(
        onTap: () => _showAddDialog(platform, result, showProvider),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  // 平台标识
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: _getPlatformColor(platform).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: _getPlatformColor(platform).withOpacity(0.3),
                      ),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          config.platformIcon,
                          style: const TextStyle(fontSize: 12),
                        ),
                        const SizedBox(width: 4),
                        Text(
                          config.platformName,
                          style: TextStyle(
                            color: _getPlatformColor(platform),
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    icon: const Icon(Icons.add_circle_outline),
                    onPressed: () => _showAddDialog(platform, result, showProvider),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              
              // 演出信息
              Text(
                _getResultTitle(platform, result),
                style: Theme.of(context).textTheme.titleMedium?.copyWith(
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              
              if (_getResultSubtitle(platform, result) != null) ...[
                const SizedBox(height: 4),
                Text(
                  _getResultSubtitle(platform, result)!,
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Colors.grey[600],
                  ),
                ),
              ],
              
              const SizedBox(height: 8),
              
              // 详细信息
              if (_getResultVenue(platform, result) != null) ...[
                Row(
                  children: [
                    Icon(Icons.location_on, size: 16, color: Colors.grey[500]),
                    const SizedBox(width: 4),
                    Expanded(
                      child: Text(
                        _getResultVenue(platform, result)!,
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 4),
              ],
              
              if (_getResultTime(platform, result) != null) ...[
                Row(
                  children: [
                    Icon(Icons.access_time, size: 16, color: Colors.grey[500]),
                    const SizedBox(width: 4),
                    Text(
                      _getResultTime(platform, result)!,
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ],
              
              if (_getResultPrice(platform, result) != null) ...[
                const SizedBox(height: 8),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.green.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    _getResultPrice(platform, result)!,
                    style: const TextStyle(
                      color: Colors.green,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  String _getResultTitle(TicketPlatform platform, Map<String, dynamic> result) {
    switch (platform) {
      case TicketPlatform.damai:
        return result['name'] ?? result['title'] ?? '未知演出';
      case TicketPlatform.maoyan:
        return result['movieName'] ?? result['name'] ?? '未知电影';
    }
  }

  String? _getResultSubtitle(TicketPlatform platform, Map<String, dynamic> result) {
    switch (platform) {
      case TicketPlatform.damai:
        return result['artist'] ?? result['performer'];
      case TicketPlatform.maoyan:
        return result['director'] ?? result['actors'];
    }
  }

  String? _getResultVenue(TicketPlatform platform, Map<String, dynamic> result) {
    switch (platform) {
      case TicketPlatform.damai:
        return result['venue'] ?? result['cityName'];
      case TicketPlatform.maoyan:
        return result['cinemaName'] ?? '多个影院';
    }
  }

  String? _getResultTime(TicketPlatform platform, Map<String, dynamic> result) {
    switch (platform) {
      case TicketPlatform.damai:
        final showTime = result['showTime'];
        if (showTime != null) {
          final dateTime = DateTime.tryParse(showTime);
          if (dateTime != null) {
            return '${dateTime.month}/${dateTime.day} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
          }
        }
        return null;
      case TicketPlatform.maoyan:
        return result['releaseDate'] ?? result['showDate'];
    }
  }

  String? _getResultPrice(TicketPlatform platform, Map<String, dynamic> result) {
    switch (platform) {
      case TicketPlatform.damai:
        final minPrice = result['minPrice'];
        final maxPrice = result['maxPrice'];
        if (minPrice != null && maxPrice != null) {
          return '¥$minPrice - ¥$maxPrice';
        } else if (minPrice != null) {
          return '¥$minPrice 起';
        }
        return null;
      case TicketPlatform.maoyan:
        final price = result['price'];
        if (price != null) {
          return '¥$price 起';
        }
        return null;
    }
  }

  Color _getPlatformColor(TicketPlatform platform) {
    switch (platform) {
      case TicketPlatform.damai:
        return Colors.red;
      case TicketPlatform.maoyan:
        return Colors.orange;
    }
  }

  void _performSearch(String keyword) {
    if (keyword.trim().isEmpty) return;
    
    final platform = TicketPlatform.values[_tabController.index];
    context.read<ShowProvider>().search(
      platform: platform,
      keyword: keyword.trim(),
    );
  }

  void _showAddDialog(
    TicketPlatform platform,
    Map<String, dynamic> result,
    ShowProvider showProvider,
  ) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加演出'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('确定要添加以下演出吗？'),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _getResultTitle(platform, result),
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  if (_getResultSubtitle(platform, result) != null)
                    Text(_getResultSubtitle(platform, result)!),
                  if (_getResultVenue(platform, result) != null)
                    Text(_getResultVenue(platform, result)!),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              await _addShowFromResult(platform, result, showProvider);
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  Future<void> _addShowFromResult(
    TicketPlatform platform,
    Map<String, dynamic> result,
    ShowProvider showProvider,
  ) async {
    try {
      final show = await showProvider.createShowFromSearchResult(
        platform: platform,
        searchResult: result,
        config: {
          'maxConcurrency': 50,
          'retryCount': 5,
          'retryDelay': 100,
          'autoStart': false,
        },
      );

      if (show != null) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('已添加演出：${show.name}'),
              action: SnackBarAction(
                label: '查看',
                onPressed: () => Navigator.pop(context),
              ),
            ),
          );
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('添加演出失败'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('添加演出失败：$e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}